Ext.define('XTFrame.controller.system.OrganManager', {
	extend: 'Ext.app.Controller',
	init: function(){
		this.control({
			'systemOrganManagerTree': {
				itemclick: function(tree, record, item, index, e){
					var layout = tree.up('panelBorder');
					var grid = layout.down('systemOrganManagerGrid');
					grid.atorganid = record.raw ? record.raw.atorganid : record.data.atorganid;
					grid.getStore().loadPage(1);
				},
				initcomplete: function(tree){
					this.refreshOrgan(tree);
				}
			},
			'systemOrganManagerTree tool[type=refresh]': {
				click: function(o, e){
					this.refreshOrgan(o.up('systemOrganManagerTree'));
				}
			},
			'systemOrganManagerGrid': {
				beforeupdate: function(grid, win, mark, opt){
					if(mark == 'editsave'){
						this.gridEditSaveClick(grid, win, mark, opt);
					}
				},
				update: function (grid, flag){
					var layout = grid.up('panelBorder');
					this.refreshOrgan(layout.down('systemOrganManagerTree'));
				}
			}
		});
	},
	gridEditSaveClick: function(grid, win, mark, opt){
		var panel = win.down('form');
		var form = panel.getForm();
		if(win.flag == 'add'){
			var serverData = ajaxUtil.serverData("regid","reg_organid");
			if(ajaxUtil.isSucceed(serverData)){
				var organid = serverData.retData;
				var atorganid = grid.atorganid+organid+".";
				var organlevel = pubOPT.getStrCount(atorganid,".");
				form.findField("organid").setValue(organid);
				form.findField("atorganid").setValue(atorganid);
				form.findField("organlevel").setValue(organlevel);
			} else {
				Ext.xtframe.msg("提示", "保存失败！");
				opt.flag = false;
			}
		}
	},
	refreshOrgan: function(tree){
		var data, organData = ajaxUtil.executeQuery('xtframe_organ_manage_0', {atorganid:""});
		if(!ajaxUtil.isSucceed(organData)){
			Ext.xtframe.msg("提示", "机构数据获取失败！");
		} else {
			data = pubOPT.treeNodeUnil(organData.arrData, undefined, 
				{menuId: 'organid', menuName: 'organname', menuLevel: 'organlevel', atMenuId: 'atorganid'});
			tree.getRootNode().removeAll(true);
			tree.getRootNode().appendChild(data);
			tree.expandAll();
		}
	}
});